package pl.skubicha.service;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@Transactional( readOnly = true )
public class RepositoryBasedUserDetailsService implements UserDetailsService {
	
	@Autowired
	private UserService service;

	/**
	 * Returns a populated {@link UserDetails} object. The username is first
	 * retrieved from the database and then mapped to a {@link UserDetails}
	 * object.
	 */
	@Override
	public UserDetails loadUserByUsername( final String username ) throws UsernameNotFoundException {
		try {
			final pl.skubicha.domain.Users domainUser = service.findByLogin( username );

			final boolean enabled = domainUser.isStatus();
			final boolean accountNonExpired = true;
			final boolean credentialsNonExpired = true;
			final boolean accountNonLocked = domainUser.isStatus();

			final List<GrantedAuthority> grantedAuthorities = new ArrayList<GrantedAuthority>();

			if ( domainUser != null ) {
				grantedAuthorities.add( new SimpleGrantedAuthority( domainUser.getRoles().getRoleName() ) );
			}

			return new User( domainUser.getLogin(), domainUser.getPassword().toLowerCase(), enabled, accountNonExpired, credentialsNonExpired, accountNonLocked, grantedAuthorities );

		} catch ( final Exception e ) {
			throw new RuntimeException( e );
		}
	}
}